$(document).ready(function(){
	setDialog();
	closeDialog();
	//初始化表格
	$('#dataGridTable').datagrid({
		columns:[[ 
           {field:'rolesName',title:'角色名称',width:200,align:'center'}, 
           {field:'createUser',title:'记录建立者',width:createUserWidth,align:'center'},
           {field:'createTime',title:'记录建立时间',width:createTimeWidth,align:'center'},
           {field:'lastModifiedUser',title:'记录最后修改者',width:lastModifiedWidth,align:'center'},
           {field:'lastModifiedTime',title:'记录最后修改时间',width:createTimeWidth,align:'center'}
         ]]
	});	
	$('#rolesName').textbox('textbox').keydown(function (e) {
	   if (e.keyCode == 13) {
		   $('#rolesName').textbox('setValue', $(this).val());
		   queryRole();
	    }
	});
});

//保存角色
function saveRole(){
	var rolesId=$("#roleInfoDialog_roleId").val();
	var rolesName=$("#roleInfoDialog_roleName").val();
	if(rolesName==null||rolesName==''){
		sysMsgShow("角色名称不允许为空!");
		return false;
	}else{
		$.ajax({
			async : false,
			cache:false,
			type: 'post',
			dataType : "json",
			data : {
				"role.rolesId" : rolesId,
				"role.rolesName" : rolesName
			},
			url: 'sys/saveRole.action',//请求的action路径
			error: function () {
				sysErrorShow('请求失败!');
			},success:function(data){
				var messgage = rolesId?"修改成功!":"添加成功!";
				if(data.success==true){
					reloadTable();
					closeDialog();
				}else{
					messgage = data.msg;
				}
				sysMsgShow(messgage);
			}
		});
	
	}	
}

//删除系统
function delRole(){
	if($('#dataGridTable').datagrid('getSelected')){
		var ids = [];
		var cods = [];
		var selectedRow = $('#dataGridTable').datagrid('getSelections');
		for(var i=0;i<selectedRow.length;i++){
			ids.push(selectedRow[i].rolesId);
			cods.push(selectedRow[i].rolesName);
		}
		var rolesId = ids.join(',');
		$.messager.confirm('删除提示', '   删除角色后，它对应的用户、菜单、资源、面板的关系都将删除，你确定删除下列角色吗?<br/><center>'+cods.join(',')+'</center>', function(r){
				if (r){
					var url = 'sys/deleteRole.action?role.rolesId='+rolesId;
					$.ajax({
						async : false,
						cache:false,
						type: 'post',
						dataType : "json",
						url:url,
						error: function () {
							sysErrorShow('请求失败');
						},success:function(data){
							if(data.success==true){
								sysMsgShow("删除成功!");
							}else{
								sysErrorShow(data.msg);
							}
							reloadTable();
						}
					});
				}
		});
	}
	else
	{
		noSelectData();
	}
}

//查询系统
function queryRole(){
	$("#dataGridTable").datagrid('reload',{		
		'role.rolesName' : $("#rolesName").val()
	 	
	}); 
}

/**--------------操作弹出框------------------**/
//初始化模窗
function setDialog(){
	$('#roleInfoDialog').dialog({
		modal: true,
		collapsible : true,
		resizable : true,
		onClose : function(){
			resetDialog();
		}
	});
}

//打开添加或修改模窗
function openDialog_add(){ 
	$('#roleInfoDialog').dialog({
		closed: false,
		modal:true,
        title: "新增角色",
        buttons: [{
            text: '确定',
            iconCls: 'icon-ok',
            handler: saveRole
        }, {
            text: '取消',
            iconCls: 'icon-cancel',
            handler: function () {
                $('#roleInfoDialog').dialog('close');                    
            }
        }]
    });
}

//打开编辑模窗
function openDialog_edit(){
	if($('#dataGridTable').datagrid('getSelected')){
		var rolesId = $('#dataGridTable').datagrid('getSelections')[0].rolesId;
		$.getJSON("sys/findRoleById.action?role.rolesId="+rolesId,null,
		function msg(json){
			$("#roleInfoDialog_roleId").val(rolesId);
			$("#roleInfoDialog_roleName").textbox('setValue',json.object.rolesName);
			openDialog_add();
			$('#roleInfoDialog').dialog('setTitle','编辑角色'); 
		});
	}
	else
	{
		noSelectData();
	}
}


//打开设置面板窗
function openPortal(){
	$('#setPortalDialog').dialog({
		closed: false,
		modal:true,
        title: "面板权限设置",
        buttons: [{
            text: '确定',
            iconCls: 'icon-ok',
            handler: saveRolePortal
        }, {
            text: '取消',
            iconCls: 'icon-cancel',
            handler: function () {
                $('#setPortalDialog').dialog('close');
            }
        }],
        onClose: function(){
        	var portalId = "";
        	$('input[name="checkedPortal"]:checked').each(function(){ 
        		portalId += $(this).val()+','; 
        	});
        	portalIds = portalId.substring(0, portalId.length - 1);
        	var oldData = $("#oldData").val().split(",");
        	var newData = portalIds.split(",");
        	if(oldData.toString()==newData.toString()){
        		$("#setPortalTable").html('');
            	$("#save_role_Id").val('');
        	}else{
        		$.messager.confirm('提示', "是否保存？",function(r){
        			if(r){
        				$.ajax({
        					async : false,
        					cache:false,
        					type: 'post',
        					dataType : "json",
        					data: {'rolePortal.roleId':$("#save_role_Id").val(),'rolePortal.portalId':portalIds},
        					url: 'sys/saveRolePortal.action',
        					error: function () {
        						sysErrorShow('请求失败');
        					},success:function(data){
        						if(data.success==true){
        							$("#setPortalTable").html('');
        				        	$("#save_role_Id").val('');
        							sysMsgShow("保存成功!");
        						}else{
        							sysErrorShow(data.msg);
        						}
        					}
        				});
        			}else{
        				$("#setPortalTable").html('');
        	        	$("#save_role_Id").val('');
        			}
        		});
        	}
        }
    });
}

//设置面板
function setPortal(){
	if($('#dataGridTable').datagrid('getSelected')){
		var rolesId = $('#dataGridTable').datagrid('getSelections')[0].rolesId;
		$("#save_role_Id").val(rolesId);
		$.ajax({
			async : false,
			cache:false,
			type: 'post',
			dataType : "json",
			url: 'sys/getRolePortalInfo.action?role.rolesId='+rolesId,
			error: function () {
				sysErrorShow('请求失败');
			},success:function(data){
				if(data.success==true){
					$("#setPortalTable").append(data.object);
				}else{
					sysErrorShow(data.msg);
				}
			}
		});
		openPortal();
		var portalId = "";
		$('input[name="checkedPortal"]:checked').each(function(){ 
			portalId += $(this).val()+','; 
		});
		portalIds = portalId.substring(0, portalId.length - 1);
		$("#oldData").val(portalIds);
	} else {
		noSelectData();
	}
}
//保存角色和面板关系
function saveRolePortal(){
	var portalId = "";
	$('input[name="checkedPortal"]:checked').each(function(){ 
		portalId += $(this).val()+','; 
	});
	portalIds = portalId.substring(0, portalId.length - 1);
	$.ajax({
		async : false,
		cache:false,
		type: 'post',
		dataType : "json",
		data: {'rolePortal.roleId':$("#save_role_Id").val(),'rolePortal.portalId':portalIds},
		url: 'sys/saveRolePortal.action',
		error: function () {
			sysErrorShow('请求失败');
		},success:function(data){
			if(data.success==true){
				sysMsgShow("保存成功!");
				$('#setPortalDialog').dialog('close');
			}else{
				sysErrorShow(data.msg);
			}
		}
	});
}

/**--------------操作弹出框------------------**/
//关闭模窗
function closeDialog(){
	$('#roleInfoDialog').dialog('close');
}

//清空控件值
function resetDialog(){
	$("#roleInfoDialog_roleId").val('');
	$("#roleInfoDialog_roleName").textbox('setValue','');
}

//刷新表格
function reloadTable(){
	$('#dataGridTable').datagrid('reload');
}

//刷新
function reloadRole()
{
	$("#rolesName").textbox('setValue','');
	queryRole();
}